// @ts-nocheck
/* eslint-disable react/prop-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
// 自定义 Table 组件 联动 金额出参 头行保存
import React, { useState, useCallback, FC, useMemo, useEffect, useRef } from 'react';

import { observer } from 'mobx-react-lite';
import { Button, Table, DataSet } from 'choerodon-ui/pro';
import { ColumnProps } from 'choerodon-ui/pro/lib/table/Column';
import { getResponse } from 'utils/utils';
import notification from 'utils/notification';
import { TableListDataSetConfig, saveAll } from './store';

interface IParams {
  [_: string]: any;
  formDataSet: DataSet;
}

const CustomTable: FC<IParams> = props => {
  const {
    headerId, // 头表单 id
    handleChangeOutputParams, //? 预置 修改出参函数
    handleRunEvent, //? 预置 调用事件流函数
    setEventFunction, //? 预置 设置内置函数
  } = props;

  const dataSet = useMemo(() => new DataSet(TableListDataSetConfig()), []);

  useEffect(() => {
    const query = async () => {
      if (!headerId) return;
      dataSet.setQueryParameter('headerId', headerId);
      await dataSet.query();
    };
    query();
    setEventFunction?.('query', (wenben1, lineNum, singleMoney) => {
      dataSet.setQueryParameter('headerId', headerId);
      dataSet.setQueryParameter('wenben1', wenben1);
      dataSet.setQueryParameter('lineNum', lineNum);
      dataSet.setQueryParameter('singleMoney', singleMoney);
      dataSet.query().then(() => {
        dataSet.setQueryParameter('wenben1', undefined);
        dataSet.setQueryParameter('lineNum', undefined);
        dataSet.setQueryParameter('singleMoney', undefined);
      });
    });
  }, [headerId]);

  useEffect(() => {
    const load = ({ dataSet }) => {
      const totalMoney = (dataSet.toData() as any[]).reduce((t, c) => {
        if (!Number.isNaN(+c.singleMoney)) {
          t += c.singleMoney;
        }
        return t;
      }, 0);
      handleChangeOutputParams({
        property: 'totalMoney',
        data: totalMoney,
      });
    };

    const update = ({ name, record }) => {
      if (name === 'singleMoney') {
        // 金额总和
        const totalMoney = (record.dataSet.toData() as any[]).reduce((t, c) => {
          if (!Number.isNaN(+c.singleMoney)) {
            t += c.singleMoney;
          }
          return t;
        }, 0);
        // 将计算的值设置出参上
        handleChangeOutputParams({
          property: 'totalMoney',
          data: totalMoney,
        });
        // 调用赋值金额总和事件流
        if ((changeMoney as any)?.flowCode) {
          handleRunEvent(changeMoney.flowCode);
        }
      }
    };

    dataSet.addEventListener('load', load);
    dataSet.addEventListener('update', update);

    return () => {
      dataSet.removeEventListener('load', load);
      dataSet.removeEventListener('update', update);
    };
  }, [dataSet]);

  const commands = useCallback(() => {
    return ['delete'];
  }, []);

  const handleTotalSave = async () => {
    if (!formDataSet) return;
    const formFlag = await formDataSet.validate();
    if (!formFlag) return;
    const tableFlag = await dataSet.validate();
    if (!tableFlag) return;
    const formData = formDataSet.toData();
    const tableData = dataSet.toData();
    const bodyData = {
      ...(formData?.[0] || {}),
      lineData: tableData,
    };

    const businessObjectRelation = {
      businessObjectCode: 'WYTST_CUSTOM_TEST_HEADER1',
      componentRelationHeads: [
        {
          businessObjectCode: 'WYTST_CUSTOM_TEST_LINE1',
          displayCode: 'lineData',
          componentRelationLines: [{ field: 'headerId', parentField: 'id' }],
        },
      ],
    };
    console.log(
      'formData tableData',
      formData,
      tableData,
      bodyData,
      businessObjectRelation,
    );
    const res = await saveAll({
      header: {
        'business-object-relation': JSON.stringify(businessObjectRelation),
      },
      body: [bodyData],
    });
    if (getResponse(res)) {
      notification.success({
        message: '保存成功',
      });
      const isCreate = !headerIdRef.current;
      if (!isCreate) {
        if ((flowFormQuery as any)?.flowCode) {
          await handleRunEvent(flowFormQuery.flowCode);
        }
        await dataSet.query();
      }
    }
  };

  createRef.current = handleAdd;
  saveRef.current = handleTotalSave;

  useEffect(() => {
    setEventFunction?.('save', saveRef.current);
    setEventFunction?.('add', createRef.current);
    setEventFunction?.('delete', () => {
      if(!dataSet.selected.length) {
        notification.warning({
          description: '请选择需要删除的数据',
        });
        return;
      }
      dataSet.delete(dataSet.selected);
    });
  }, []);

  const buttons = [
    <Button icon="save" onClick={handleTotalSave} key="save">
      头行保存
    </Button>,
    <Button icon="playlist_add" onClick={handleAdd} key="add">
      新增
    </Button>,
    <Button
      key="delete"
      icon="delete_black-o"
      onClick={() => {
        dataSet.delete(dataSet.selected, true);
      }}
      disabled={dataSet.selected.length === 0}
    >
      批量删除
    </Button>,
  ].filter(Boolean);

  const columns: ColumnProps[] = [
    { name: 'singleMoney', editor },
    { name: 'lineNum', editor },
    { name: 'wenben1', editor },
    { header: '操作', align: 'center', command: commands, lock: 'right' },
  ];

  return (
    <Table
      key="user"
      buttons={buttons}
      dataSet={dataSet}
      columns={columns}
      queryBar="filterBar"
    />
  );
};

export default observer(CustomTable);
